﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using ActivityTracker.Library;
using System.Windows.Navigation;
using Common.Library;

namespace ActivityTracker.Views.Themes
{
    public partial class Photo_Chooser : PhoneApplicationPage
    {
        Rectangle ClipRect;
        private double TotalImageScale = 1d;
        private Point ImagePosition = new Point(0, 0);
        private const double MAX_IMAGE_ZOOM = 5;
        private Point _oldFinger1;
        private Point _oldFinger2;
        private double _oldScaleFactor;
        BitmapImage image = new BitmapImage();
        string type;
        public Photo_Chooser()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(Photo_Chooser_Loaded);

        }

        void Photo_Chooser_Loaded(object sender, RoutedEventArgs e)
        {
          
           
            type = SettingsHelper.getStringValue("type");
            ImgZoom.Source = App.AcitivityImgSrc;
            ImgZoom.Stretch = Stretch.UniformToFill;
            
                ClipRect = new Rectangle();
                ClipRect.Fill = new SolidColorBrush(Colors.Transparent);
            if (type == "Activity")
            {
                ApplicationTitle1.Text = "Add Activity";
                ApplicationTitle1.FontSize = ApplicationTitle.FontSize;
                ClipRect.Height = 100;
                ClipRect.Width = 100;
                ImgZoom.Width = 100;
                ImgZoom.Height = 100;
                ContentPanel.Width = ImgZoom.Width;
                ContentPanel.Height = ImgZoom.Height;

                

            }
            else
            {
                ApplicationTitle1.Text = "Choose BackGround";
                ApplicationTitle1.FontSize = ApplicationTitle.FontSize;
                ClipRect.Height = 300;
                ClipRect.Width = 400;
                ContentPanel.Width = ImgZoom.Width;
                ContentPanel.Height = ImgZoom.Height;

            }
           
            ClipRect.Stroke = new SolidColorBrush(Colors.Red);
            ClipRect.StrokeThickness = 5;
           
            ContentPanel.Children.Add(ClipRect);
            
            ApplicationBar.IsMenuEnabled = true;
            if (type == "Activity")
            {
                ApplicationBar.IsMenuEnabled = false;
                
            }
            
        }
        
        private void Accept_Click(object sender, EventArgs e)
        {
          
            ClipRect.Visibility = System.Windows.Visibility.Collapsed;
            WriteBitmap(ContentPanel);
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream local = myIsolatedStorage.OpenFile("myImage.jpg", FileMode.Open, FileAccess.Read))
                {

                    image.SetSource(local);
                }
            }
            ImgZoom.Stretch = Stretch.UniformToFill;
            ImgZoom.Source = image;
            ResetImagePosition();
            ClipRect.Visibility = System.Windows.Visibility.Visible;
            ClipImage();
            WriteBitmap1(ImgZoom);
          
             SettingsHelper.Save("Nav", "0");
            if (type == "Activity")
            {
                 SettingsHelper.Save("type", "");
                 SettingsHelper.Save("back", "back");
                NavigationService.GoBack();
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/Themes/BackgroundSelection.xaml", UriKind.Relative));
            }
           
        }
        void ClipImage()
        {
            RectangleGeometry geo = new RectangleGeometry();
            GeneralTransform gt = ClipRect.TransformToVisual(ContentPanel);
            Point p = gt.Transform(new Point(0, 0));
            geo.Rect = new Rect(p.X, p.Y, ClipRect.Width, ClipRect.Height);
            ImgZoom.Clip = geo;
            ClipRect.Visibility = System.Windows.Visibility.Collapsed;
        }
        void WriteBitmap1(FrameworkElement element)
        {
            string filePath=string.Empty;

            WriteableBitmap wBitmap = new WriteableBitmap(element, null);
            using (MemoryStream stream = new MemoryStream())
            {
                if (type == "Activity")
                {
                    wBitmap.SaveJpeg(stream, 100, 100, 0, 100);
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!myIsolatedStorage.DirectoryExists("ActivityTracker/ActivityImages"))

                            myIsolatedStorage.CreateDirectory("ActivityTracker/ActivityImages");

                        filePath = System.IO.Path.Combine("ActivityTracker/ActivityImages", App.actName + ".jpg");

                        if (myIsolatedStorage.FileExists(filePath))
                            myIsolatedStorage.DeleteFile(filePath);
                        using (IsolatedStorageFileStream local = myIsolatedStorage.CreateFile(filePath))
                        {

                            local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
                            //IsolatedSettings.save("write","true");
                           
                        }
                    }

                }
                else
                {
                    wBitmap.SaveJpeg(stream, 1024, 768, 0, 100);

                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (myIsolatedStorage.FileExists("myImage1.jpg"))
                        {
                            myIsolatedStorage.DeleteFile("myImage1.jpg");
                        }

                        using (IsolatedStorageFileStream local = myIsolatedStorage.CreateFile("myImage1.jpg"))
                        {

                            local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
                        }
                    }
                }

            }
        }
        
        void WriteBitmap(FrameworkElement element)
        {

            
            WriteableBitmap wBitmap = new WriteableBitmap(element, null);
            using (MemoryStream stream = new MemoryStream())
            {
                wBitmap.SaveJpeg(stream, (int)ContentPanel.RenderSize.Width, (int)ContentPanel.RenderSize.Height, 0, 100);
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (myIsolatedStorage.FileExists("myImage.jpg"))
                    {
                        myIsolatedStorage.DeleteFile("myImage.jpg");
                    }
                    using (IsolatedStorageFileStream local = myIsolatedStorage.CreateFile("myImage.jpg"))
                    {
                    
                        local.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
                    }
                }
                
            }
        }

        #region Event handlers

        private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
        {
            _oldFinger1 = e.GetPosition(ImgZoom, 0);
            _oldFinger2 = e.GetPosition(ImgZoom, 1);
            _oldScaleFactor = 1;
        }


        private void OnPinchDelta(object sender, PinchGestureEventArgs e)
        {
            var scaleFactor = e.DistanceRatio / _oldScaleFactor;
            if (!IsScaleValid(scaleFactor))
                return;

            var currentFinger1 = e.GetPosition(ImgZoom, 0);
            var currentFinger2 = e.GetPosition(ImgZoom, 1);

            var translationDelta = GetTranslationDelta(
                currentFinger1,
                currentFinger2,
                _oldFinger1,
                _oldFinger2,
                ImagePosition,
                scaleFactor);

            _oldFinger1 = currentFinger1;
            _oldFinger2 = currentFinger2;
            _oldScaleFactor = e.DistanceRatio;

            UpdateImageScale(scaleFactor);
            UpdateImagePosition(translationDelta);
        }


        private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            var translationDelta = new Point(e.HorizontalChange, e.VerticalChange);

            if (IsDragValid(1, translationDelta))
                UpdateImagePosition(translationDelta);
        }


        private void OnDoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ResetImagePosition();
        }

        #endregion
        #region Utils

        private Point GetTranslationDelta(
            Point currentFinger1, Point currentFinger2,
            Point oldFinger1, Point oldFinger2,
            Point currentPosition, double scaleFactor)
        {
            var newPos1 = new Point(
             currentFinger1.X + (currentPosition.X - oldFinger1.X) * scaleFactor,
             currentFinger1.Y + (currentPosition.Y - oldFinger1.Y) * scaleFactor);

            var newPos2 = new Point(
             currentFinger2.X + (currentPosition.X - oldFinger2.X) * scaleFactor,
             currentFinger2.Y + (currentPosition.Y - oldFinger2.Y) * scaleFactor);

            var newPos = new Point(
                (newPos1.X + newPos2.X) / 2,
                (newPos1.Y + newPos2.Y) / 2);

            return new Point(
                newPos.X - currentPosition.X,
                newPos.Y - currentPosition.Y);
        }


        private void UpdateImageScale(double scaleFactor)
        {
            TotalImageScale *= scaleFactor;
            ApplyScale();
        }


        private void ApplyScale()
        {
            ((CompositeTransform)ImgZoom.RenderTransform).ScaleX = TotalImageScale;
            ((CompositeTransform)ImgZoom.RenderTransform).ScaleY = TotalImageScale;

        }

        private void UpdateImagePosition(Point delta)
        {
            var newPosition = new Point(ImagePosition.X + delta.X, ImagePosition.Y + delta.Y);

            if (newPosition.X > 0) newPosition.X = 0;
            if (newPosition.Y > 0) newPosition.Y = 0;

            if ((ImgZoom.ActualWidth * TotalImageScale) + newPosition.X < ImgZoom.ActualWidth)
                newPosition.X = ImgZoom.ActualWidth - (ImgZoom.ActualWidth * TotalImageScale);

            if ((ImgZoom.ActualHeight * TotalImageScale) + newPosition.Y < ImgZoom.ActualHeight)
                newPosition.Y = ImgZoom.ActualHeight - (ImgZoom.ActualHeight * TotalImageScale);

            ImagePosition = newPosition;

            ApplyPosition();
        }

        private void ApplyPosition()
        {
            ((CompositeTransform)ImgZoom.RenderTransform).TranslateX = ImagePosition.X;
            ((CompositeTransform)ImgZoom.RenderTransform).TranslateY = ImagePosition.Y;
        }


        private void ResetImagePosition()
        {
            TotalImageScale = 1;
            ImagePosition = new Point(0, 0);
            ApplyScale();
            ApplyPosition();
        }


        private bool IsDragValid(double scaleDelta, Point translateDelta)
        {
            if (ImagePosition.X + translateDelta.X > 0 || ImagePosition.Y + translateDelta.Y > 0)
                return false;

            if ((ImgZoom.ActualWidth * TotalImageScale * scaleDelta) + (ImagePosition.X + translateDelta.X) < ImgZoom.ActualWidth)
                return false;

            if ((ImgZoom.ActualHeight * TotalImageScale * scaleDelta) + (ImagePosition.Y + translateDelta.Y) < ImgZoom.ActualHeight)
                return false;

            return true;
        }


        private bool IsScaleValid(double scaleDelta)
        {
            return (TotalImageScale * scaleDelta >= 1) && (TotalImageScale * scaleDelta <= MAX_IMAGE_ZOOM);
        }

        #endregion
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            App.AcitivityImgSrc = null;

        }
       
        

    }
}